package cn.jiedanba.cacert.common.exception;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.jiedanba.cacert.common.result.ResponseResult;

@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(BindException.class)
	@ResponseBody
	public ResponseResult bindExceptionHandler(BindException e) {
		List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
		String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
		List<String> msgList = new ArrayList<>();
		msgList = Arrays.asList(message.split(";"));
		return ResponseResult.fail(msgList.get(0));
	}

	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	@ResponseBody
	public ResponseResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
		List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
		String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
		List<String> msgList = new ArrayList<>();
		msgList = Arrays.asList(message.split(";"));
		return ResponseResult.fail(msgList.get(0));
	}

}
